%% @author Carlos Abalde <carlos.abalde@gmail.com>
%% @doc    Basic local event console logger

%%%----------------------------------------------------------------------
%%%
%%% EMC, Copyright (C) 2009 Carlos Abalde
%%%
%%% This program is free software; you can redistribute it and/or
%%% modify it under the terms of the GNU General Public License as
%%% published by the Free Software Foundation; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%%% General Public License for more details.
%%%
%%% You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
%%% 02111-1307 USA
%%%
%%%----------------------------------------------------------------------

-module(emc.util.console_logger).
-behaviour(gen_event).

-import(gen_event).
-import(lists).
-import(erlang).
-import(io_lib).
-import(io).
-import(calendar).
-import(emc.util.util).

%% gen_event callbacks
-export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]).

-include("emc.hrl").

-record(state, { types }).

%%-------------------------------------------------------------------------------
%% gen_event callbacks
%%-------------------------------------------------------------------------------

%%
%%
%%
init(Types) ->
    State0 = #state{ types = Types },
    {ok, State0}.

%%
%%
%%
handle_event(#event{} = Event, State) ->
    {ok, NewState} = do_log(State, Event),
    {ok, NewState};

handle_event(_, State) ->
    {ok, State}.

%%
%%
%%
handle_call(_, State) ->
    {ok, ok, State}.

%%
%%
%%
handle_info(_, State) ->
    {ok, State}.

%%
%%
%%
terminate(_, _) ->
    ok.

%%
%%
%%
code_change(_, State, _) ->
    {ok, State}.

%%%-----------------------------------------------------------------------------
%%% Callback implementation
%%%-----------------------------------------------------------------------------

%%
%%
%%
do_log(State, Event) ->
    case lists:member(Event#event.type, State#state.types) of
	true ->
	    Message = io_lib:format("[~p][~p][~p] ~s", [Event#event.type, Event#event.source, Event#event.pid, Event#event.data]),
	    write_log(calendar:now_to_local_time(Event#event.timestamp), Message);
	false ->
	    true
    end,
    {ok, State}.

%%%-----------------------------------------------------------------------------
%%% Internal implementation
%%%-----------------------------------------------------------------------------

%%
%%
%%
write_log({{Year, Month, Day}, {H, M, S}}, Message) ->
    io:format("[~2..0w/~2..0w/~4..0w ~2..0w:~2..0w:~2..0w] ~s~n", [Day, Month, Year, H, M, S, Message]).
